import { saveAs } from 'file-saver'
import { saveFile, Globalize } from '@grapecity/wijmo'
import { DataMap, CellRange } from '@grapecity/wijmo.grid'
import { showPopup, hidePopup, hasClass, closest, createElement, getElement, removeChild } from '@grapecity/wijmo'

import { objectArrValue } from '../Utils/Common'
import { Http } from '../API'

// 刷新数据
const onRefresh = ({ init, InitWijmo }) => init(InitWijmo.init, true)
// 添加数据
const onAdded = ({ setOptionsCall, columns }) => setOptionsCall({ type: 'FormAdded', title: '新增数据', data: columns })
// 删除数据
const onDelete = ({ setOptionsCall, Data }) => setOptionsCall({ type: 'FormDelete', title: '删除警告!', data: Data.currentItem, width: 600 })
// 修改数据
const onModify = ({ setOptionsCall, columns, Data }) => setOptionsCall({ type: 'FormModify', title: '修改数据', data: { columns, item: Data.currentItem } })
// 查询数据
const onSearch = ({ setDrawerCall, Search, SearchData }) => {
    setDrawerCall({ type: 'SearchBox', title: '条件检索', data: { columns: Search, initValue: SearchData } })
}
// 排序数据
const onSort = ({ setDrawerCall, sortCriteria, InitWijmo, SortData }) => {
    setDrawerCall({ type: 'SortBox', title: '排序条件', data: { sortCriteria, init: InitWijmo.initSort, SortData } })
}
// 图片列表
const onAnnexImageList = ({ setOptionsCall, Data, btnData }) => {
    setOptionsCall({ type: 'AnnexImageList', title: '附件信息', data: { btnData, record: Data.currentItem } })
}
// 审核数据
const onExamine = ({ setOptionsCall, Data, btnData, init, InitWijmo }) => {
    setOptionsCall({ type: 'FormExamine', title: '审核信息', data: { btnData, record: Data.currentItem, init, InitWijmo } })
}
// 数据中控 olap
const onOLAP = ({ setDrawerCall, InitWijmo, initCom, combination }) => {
    setDrawerCall({
        type: 'WijmoPivotPanel',
        title: '数据控制台',
        placement: 'left',
        width: 800,
        data: { itemsSource: InitWijmo.Data, initCom, combination },
    })
}
// 数据图表
const onChart = ({ setOptionsCall, InitWijmo }) => {
    setOptionsCall({
        type: 'WijmoPivotChart',
        title: '数据图例',
        width: '90vw',
        data: { itemsSource: InitWijmo.Data },
    })
}
// 导出选中数据
const onSaveAct = ({ InitWijmo }) => saveFile(InitWijmo.init.getClipString(null, true, true), '选中数据.csv')
// 导出全部数据
const onSaveAll = ({ InitWijmo }) => {
    const rng = new CellRange(0, 0, InitWijmo.init.rows.length - 1, InitWijmo.init.columns.length - 1)
    saveFile(InitWijmo.init.getClipString(rng, true, true), '全部数据.csv')
}
// 导出模板数据
const onSaveAdm = ({ SearchData, params, btnData }) => {
    const file = { ...SearchData, ...params }
    const { url, search } = btnData
    Http({ url, params: search ? file : {}, responseType: 'blob' }).then(res => saveAs(res.blob, res.filename))
}
// 通用函数
const onModelBox = ({ ModalEvent, btnData }) => {
    ModalEvent.emit({ type: 'ModelBox', data: btnData })
}

// 修改状态
const onModifyStatus = ({ setOptionsCall, Data, btnData }) => {
    console.log('修改状态')
}



// 右键操作
export const eventHandlers = {
    onRefresh,
    onAdded,
    onDelete,
    onModify,
    onSaveAct,
    onSaveAll,
    onSearch,
    onSort,
    onAnnexImageList,
    onExamine,
    onOLAP,
    onChart,
    onSaveAdm,
    onModelBox,
    onModifyStatus
}

// 初始化搜索参数
export const initSearchValue = (columns) => {
    const init = columns.reduce((accumulator, { dataIndex, initialValue }) => {
        if (initialValue) { accumulator[dataIndex] = initialValue }
        return accumulator
    }, {})
    return init
}
export const initSortValue = (sortCriteria) => {
    if (sortCriteria) return sortCriteria.reduce((acc, item) => {
        if (item.default) { acc[item.value] = item.default }
        return acc
    }, {})
    else return []
}

// 初始化函数
export const initTopDom = (e, InitWijmo) => {
    const ref = e.hostElement.querySelector(".wj-topleft")
    ref.addEventListener("mousedown", e => {
        if (hasClass(e.target, "TopText")) {
            let host = InitWijmo.columnPicker.hostElement
            if (!host.offsetHeight) {
                showPopup(host, ref, false, true, false)
                InitWijmo.columnPicker.focus()
            }
            else {
                hidePopup(host, true, true)
                InitWijmo.flex.focus()
            }
            InitWijmo.columnPicker.focus()
            e.preventDefault()
        }
    })
}


export const initListBox = (init, InitWijmo) => {
    const host = init.hostElement
    host.addEventListener('dragstart', e => handleDragStart(e, InitWijmo));
    host.addEventListener('dragover', e => handleDragOver(e, InitWijmo));
    host.addEventListener('drop', e => handleDrop(e, InitWijmo));
    host.addEventListener('dragend', () => handleDragEnd(InitWijmo));
    InitWijmo.columnPicker = init
    if (InitWijmo.init) {
        InitWijmo.columnPicker.itemsSource = InitWijmo.init.columns;
        InitWijmo.columnPicker.checkedMemberPath = 'visible';
        InitWijmo.columnPicker.displayMemberPath = 'header';
        InitWijmo.columnPicker.lostFocus.addHandler(() => hidePopup(InitWijmo.columnPicker.hostElement))
        InitWijmo.columnPicker.formatItem.addHandler((s, e) => enableDragItem(e.item))
    }
}
const enableDragItem = (item) => {
    item.setAttribute('draggable', 'true')
}
const handleDragStart = (e, InitWijmo) => {
    InitWijmo.dragSrc = closest(e.target, '.wj-listbox-item')
    if (InitWijmo.dragSrc) {
        e.dataTransfer.setData('text', InitWijmo.dragSrc.innerHTML)
        e.dataTransfer.effectAllowed = 'move';
    }
}
const handleDragOver = (e, InitWijmo) => {
    const dragOver = closest(e.target, '.wj-listbox-item')
    if (InitWijmo.dragDst && InitWijmo.dragDst !== dragOver) removeDropMarker()
    if (dragOver && dragOver !== InitWijmo.dragSrc) {
        e.preventDefault()
        e.dataTransfer.dropEffect = 'move'
        InitWijmo.dragDst = dragOver
        const src = getElementIndex(InitWijmo.dragSrc);
        const dst = getElementIndex(InitWijmo.dragDst);
        removeDropMarker();
        addDropMarker(dst > src, InitWijmo);
    }
    else InitWijmo.dragDst = null

}
const handleDrop = (e, InitWijmo) => {
    if (InitWijmo.dragSrc && InitWijmo.dragDst) {
        e.preventDefault();
        const src = getElementIndex(InitWijmo.dragSrc);
        const dst = getElementIndex(InitWijmo.dragDst);
        InitWijmo.init.columns.moveElement(src, dst);
    }
}
const handleDragEnd = (InitWijmo) => {
    InitWijmo.dragSrc = null
    InitWijmo.dragDst = null
    removeDropMarker()
}
const removeDropMarker = () => {
    removeChild(getElement('.drop-marker'))
}
const getElementIndex = (element) => {
    const parent = element.parentElement;
    const siblings = Array.prototype.slice.call(parent.children);
    return siblings.indexOf(element);
}
const addDropMarker = (isAfterPos, InitWijmo) => {
    const itemsGap = 10;
    const width = 6;
    const margin = itemsGap / width;
    const height = InitWijmo.dragDst.clientHeight;
    const topPos = InitWijmo.dragDst.offsetTop;
    const leftPos = isAfterPos
        ? (InitWijmo.dragDst.offsetLeft + InitWijmo.dragDst.clientWidth + margin)
        : (InitWijmo.dragDst.offsetLeft - itemsGap + margin);
    const css = `top:${topPos}px;left:${leftPos}px;height:${height}px;width:${width}px`
    const html = `<div class="drop-marker" style="${css}">&nbsp</div>`
    createElement(html, InitWijmo.columnPicker.hostElement)
}

export const getDataMap = (e, mapping) => {
    if (e) {
        let value = mapping?.value || 'value'
        let label = mapping?.label || 'label'
        return new DataMap(e, value, label)
    }
}

export const CustonGroup = (e, columns) => {
    if (e.col.aggregate !== 0) {
        const { aggTitle, smlTitle, format } = objectArrValue(columns, e.col.binding, 'dataIndex')
        if (e.item) return `${smlTitle} : ${Globalize.formatNumber(e.value, format)}`
        else return `${aggTitle} : ${Globalize.formatNumber(e.value, format)}`
    }
}

